//
//  YWUnAssignPostTroubleTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWUnAssignPostTroubleTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "NSDate+YYAdd.h"
#import "MJRefresh.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"

#import "UITableView+FDTemplateLayoutCell.h"
//#import "YWMyPostTroubleCell.h"
#import "YWPostTroublesBillsCell.h"

#import "YWMission.h"

#import "YWMissionManager.h"
#import "YWCirculationDetailViewController.h"
#import "YWEwinManager.h"
#import "YWNavigationController.h"
#import "YWAssignTroubleMissionTableViewController.h"
//#import "YWReplyManager.h"
//#import "YWNoReadReplyTableViewController.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWNotifyManager.h"

@interface YWUnAssignPostTroubleTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,YWPostTroublesBillsCellDelegate>{
    NSInteger page;
}
@property (nonatomic, strong) NSMutableArray *tempDataArray;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation YWUnAssignPostTroubleTableViewController
//- (instancetype)init{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self setupNotifications];
    [self setupTableView];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostRefreshCirculationDetailVCNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostCirculationHandlerNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KPostNoQrcodePostTroubleNotification object:nil];
    [[YWNotifyManager shareManager] addPostTroubleObserver:self selector:@selector(refreshTableView:)];
}

- (void)setupTableView{
    page = 1;
    [self.tableView registerClass:[YWPostTroublesBillsCell class] forCellReuseIdentifier:YWPostTroublesBillsCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
}

- (void)refreshTableView:(id)sender{
    [self refreshTop];
//    _dataSource = nil;
//    [self.tableView reloadData];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
//        _dataSource = [[NSArray alloc] initWithArray:[[YWReportTroubleManager shareManager] getMyReportTroubleWithAssignStatus:NO page:page]];
    }
    return _dataSource;
}

- (NSMutableArray*)tempDataArray{
    if (!_tempDataArray) {
        _tempDataArray = [NSMutableArray array];
    }
    return _tempDataArray;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [self.dataSource  count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource[section]  count];
}

#pragma mark - UITableViewDelegate mothods

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWPostTroublesBillsCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroublesBillsCell *cell) {
//        cell.fd_enforceFrameLayout = NO;
//        cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
//    }];
//}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWPostTroublesBillsCell *cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroublesBillsCellIdentifier];
    cell.delegate = self;
    cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    return cell;
}

#pragma mark - UITableViewDataDelegate mothods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWCirculationDetailViewController *circulationDetailVC = [[YWCirculationDetailViewController alloc] init];
    YWReportTroubleModel * reportTrouble= self.dataSource[indexPath.section][indexPath.row];
    YWReportTroubleModel * cirReportTrouble = [[YWReportTroubleManager shareManager] getOneReportTroubleWithTroubleId:reportTrouble.troubleId];
    circulationDetailVC.troubleMissionModel = cirReportTrouble.troubleMission;
    [self.navigationController pushViewController:circulationDetailVC animated:YES];
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWUnAssignPostTroubleTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *temp = self.dataSource[section];
    YWReportTroubleModel * reportTrouble = temp.count ? temp[0] : nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:reportTrouble.reportTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

#pragma mark - YWGrabTroubleBillCellDelegate
- (void)clickAssignBillEvent:(UITableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YWAssignTroubleMissionTableViewController * detailVC = [[YWAssignTroubleMissionTableViewController alloc] init];
    YWReportTroubleModel *reportTroulbe = self.dataSource[indexPath.section][indexPath.row];
    YWReportTroubleModel * cirReportTrouble = [[YWReportTroubleManager shareManager] getOneReportTroubleWithTroubleId:reportTroulbe.troubleId];
    detailVC.troubleMissionModel = cirReportTrouble.troubleMission;;
    [self.navigationController pushViewController:detailVC animated:YES];
}


- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __block NSInteger dataCount = 0;
        if (refreshType == YWTableViewFreshTypeUp) {
            page++;
        }

        [[YWReportTroubleManager shareManager] requestReportTroubleWithPage:page pageSize:10 troubleStatus:[NSString stringWithFormat:@"%lu",(unsigned long)YWTroubleMissionStatusUnAssign] completeBlock:^(NSArray *reportTroubleArray) {
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tempDataArray removeAllObjects];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            dataCount += reportTroubleArray.count;
            [weakSelf.tempDataArray addObjectsFromArray:reportTroubleArray];
            [weakSelf.dataSource removeAllObjects];
            //按照时间构建二维数组
            __block NSString *lastDate = nil;
            __block NSMutableArray *array = nil;
            __block NSMutableArray * troubleArray = [NSMutableArray array];
            [weakSelf.tempDataArray enumerateObjectsUsingBlock:^(YWReportTroubleModel * _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *timeDate = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
                if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                    lastDate = timeDate;
                    array = [NSMutableArray array];
                }
                [array addObject:reportTrouble];
                if (![troubleArray containsObject:array] && array.count) {
                    [troubleArray addObject:array];
                }
            }];
            
            [weakSelf.dataSource addObjectsFromArray:troubleArray];
            [weakSelf.tableView reloadData];
            
            if (dataCount>0) {
                NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
                [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeTrouble];
            }
        }];
        
//        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (refreshType == YWTableViewFreshTypeDown) {
//                [weakSelf.tableView.mj_header endRefreshing];
//            }
//            else {
//                [weakSelf.tableView.mj_footer endRefreshing];
//            }
//            
//            weakSelf.dataSource = nil;
//            [weakSelf.tableView reloadData];
//        });
    });
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
